﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace 串口转发
{
    namespace Communication.UDPClient
    {
        public class UdpStateEventArgs : EventArgs
        {
            public IPEndPoint remoteEndPoint;
            public byte[] buffer = null;
        }

        public delegate void UDPReceivedEventHandler(UdpStateEventArgs args);

        public class UDPClient
        {
            private UdpClient udpClient;
            public event UDPReceivedEventHandler UDPMessageReceived;

            private bool IsRunning = false;
            private bool IsStoped = false;

            public UDPClient(string locateIP, int locatePort)
            {
                udpClient = new UdpClient(locatePort);

                //监听创建好后，创建一个线程，开始接收信息
                Task.Run(() =>
                {
                    IsRunning = true; 
                    while (!IsStoped)
                    {
                        UdpStateEventArgs udpReceiveState = new UdpStateEventArgs();

                        if (udpClient != null)
                        {
                            IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, locatePort);
                            var received = udpClient.Receive(ref remotePoint);
                            udpReceiveState.remoteEndPoint = remotePoint;
                            udpReceiveState.buffer = received;
                            UDPMessageReceived?.Invoke(udpReceiveState);
                        }
                        else
                        {
                            break;
                        }
                    }

                    IsRunning = false;
                });
            }

            public void Stop()
            {
                IsStoped = true;
                while (IsRunning) ;
                udpClient.Close();
            }
        }
    }
}
